import store, {defaultState} from "@/store";
import CryptoJS from "crypto-js";
import getLoction from "@/utils/getLoction";


export const setPhone = (phone) => { //隐私手机号
    return phone.substr(0, 3) + '****' + phone.substr(7)
}
/**
 * 字符串转Base64
 * @param str
 * @returns {string}
 */
export const stringToBase64 = (str) => {
    // 将字符串转换为ArrayBuffer
    var buffer = new ArrayBuffer(str.length);
    var view = new Uint8Array(buffer);
    for (var i = 0; i < str.length; i++) {
        view[i] = str.charCodeAt(i);
    }
    return uni.arrayBufferToBase64(buffer);
}
export const md5Encrypt = (text) => {
    let h = CryptoJS.MD5(text).toString(CryptoJS.enc.Hex).slice(0, 16).toUpperCase();
    return stringToBase64(h).substring(0, 16);
};
/**
 * 判断是否在微信浏览器   true是
 * @returns {boolean}
 */
export const isWeiXinBrowser = () => {
    // #ifdef H5
    // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
    let ua = window.navigator.userAgent.toLowerCase()
    // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true
    } else {
        return false
    }
    // #endif
    return false
}

export const decrypt = (encryptWord) => {
    try {
        return CryptoJS.enc.Utf8.stringify(CryptoJS.AES
            .decrypt(encryptWord, CryptoJS.enc.Utf8.parse(md5Encrypt(defaultState.key)), {
                mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7,
            })).toString();
    } catch (e) {
        return JSON.stringify(encryptWord)
        //TODO handle the exception
    }
}

export const showPrompt = function (option) {
    if (typeof option === 'object') {
        // #ifndef H5
        // if (option.hideTabBar) {
        // 	wx.hideTabBar();
        // }
        // #endif
        store.commit('showPrompt', option)
    } else {
        throw "配置项必须为对象传入的值为：" + typeof option;
    }
}
// 定义
export const goURl = (url) => { //全局跳转封装
    if (url.indexOf('/pages/') != -1) {
        if (url.indexOf('/pages/index/index') != -1 || url.indexOf('/pages/vicinity/vicinity') != -1 || url.indexOf('/pages/personal/index') != -1 || url.indexOf('/pages/commodity/category') != -1) {
            uni.switchTab({
                url: url
            })
        } else {
            uni.navigateTo({
                url: url
            })
        }
    } else if (url.indexOf('http://') != -1 || url.indexOf('https://') != -1) {
        if (url.indexOf('https://work.weixin.qq.com') != -1) {
            // #ifdef H5
            window.location.href = url
            // #endif
            // #ifdef APP-PLUS
            plus.runtime.openURL(url);
            // #endif
        } else {
            uni.setStorageSync('appletid', 0)
            uni.setStorageSync('applet', url)
            uni.navigateTo({
                url: '/pages/applet/applet'
            })
        }

    } else {
        if (url.goodsType == 0) {
            uni.navigateTo({
                url: url.link
            })
        } else if (url.goodsType == 1) {
            uni.navigateTo({
                url: `/pages/commodity/details?id=${url.link}`
            })
        } else if (url.goodsType == 2) {
            uni.navigateTo({
                url: `/pages/commodity/category?id=${url.link}`
            })
        }
        // #ifndef MP-WEIXIN
        // uni.showToast({
        // 	icon: 'none',
        // 	title: '暂未开放,敬请期待'
        // })
        // #endif

    }
}
export const gotosUrls = (obj) => { //全局跳转封装
    if (obj.link == '') {
        // #ifndef  MP-WEIXIN
        uni.showToast({
            icon: 'none', title: '暂未开放'
        })
        return false;
        //  #endif
    }
    var Tab = Tab = ['pages/index/index', '/pages/cat/cat', '/pages/personal/index', '/pages/commodity/category', '/pages/vicinity/vicinity']
    if (Tab.indexOf(obj.link) != -1) {
        uni.switchTab({
            url: obj.link
        })
        return
    }
        //暂时对外部链接不考虑
        //  else if (obj.link.indexOf("www") >= 0 || obj.link.indexOf("http") >= 0 || obj.link.indexOf("https") >= 0) {
        // 	uni.navigateTo({
        // 		url: `/pages/company/skip?url=${url}`
        // 	})
    // }
    else {
        if (obj.goodsType == 0) {
            uni.navigateTo({
                url: obj.link
            })
        } else if (obj.goodsType == 1) {
            uni.navigateTo({
                url: `/pages/commodity/details?id=${obj.link}`
            })
        } else if (obj.goodsType == 2) {
            uni.navigateTo({
                url: `/pages/commodity/partition?type=1&id=${obj.link}`
            })
        }
    }
}

export const toFiexd = (num, index) => { //保留小数
    if (num === undefined || num === null) {
        return '0.00'
    }
    if (typeof num === 'string') {
        num = parseFloat(num)
    }

    return Number(num).toFixed(index)
}
export const clearTime = (time) => { //处理时间
    return time.replace('T', ' ').split('.')[0]
}
export const toast = (str) => {
    uni.showToast({
        icon: "none", title: str
    })
}
export const isIos = () => { //判断是否ios
    let platform = uni.getSystemInfoSync().platform;
    return platform === 'ios'
}
export const isAuto = () => { //是否登录
    let token = ''
    try {
        token = uni.getStorageSync('userInfo').token
    } catch (e) {
    }
    if (token) {
        return true
    } else {
        return false
    }
}
export const sellPrice = (row) => { //处理进货价和卖价
    // let str = (((parseFloat(row.price) - parseFloat(row.amount)) / 2) + parseFloat(row.amount)).toFixed(2)
    let price = parseFloat(row.price)
    let amount = parseFloat(row.amount)
    let str = 0
    if (amount * 1.1 > price) {
        str = (price - amount) / 100 * 20 + amount
    } else {
        str = amount * 1.1
    }
    return str.toFixed(2)
}
export const userInfo = (data) => { //全局接口请求
    let token = ''
    try {
        token = uni.getStorageSync('userInfo').token
    } catch (e) {

    }
    uni.request({
        url: defaultState.baseurl + 'api/user_info/', method: 'GET', header: {
            'token': token, 'encryption': store.state.encryption
        }, success: res => {
            if (store.state.encryption) {
                try {
                    res.data.data = res.data.data ? JSON.parse(decrypt(res.data.data)) : res.data.data
                } catch (e) {
                    //TODO handle the exception
                }
            }
            if (res.statusCode == 200) {
                uni.setStorageSync('userInfo', res.data.data);
                // app.config.globalProperties.$store.state.name=res.data.data.project_name
                data && data.success && data.success(res.data);
            } else if (res.statusCode == 403) {
                uni.setStorageSync('userInfo', {});
                // #ifdef MP-WEIXIN
                uni.switchTab({
                    url: '/pages/personal/index'
                });
                // #endif
                // #ifndef MP-WEIXIN
                uni.reLaunch({
                    url: '/pages/login/login'
                });
                // #endif
            } else if (res.statusCode === 400) {
                uni.reLaunch({
                    url: '/pages/stop/stop'
                });
            } else {
            }
        }, fail(e) {
        }
    });
}
export const requsetBaseFn = (isHop = false) => {
    return (data) => { //全局接口请求
        let token = ''
        const header = {
           'token': '', 'encryption': defaultState.encryption
        }
        let p = ''
        try {
            p = uni.getStorageSync('userInfo').p
        } catch (e) {

        }
        try {
            if (isHop) {
                token = uni.getStorageSync('businessToken')
                header.business=token
            } else {
                token = uni.getStorageSync('userInfo').token;
                header.p = p
                header.token = token

            }

        } catch (e) {
            //TODO handle the exception
            console.error('Error getting token from storage:', e);
        }
        uni.request({
            url: (isHop ? defaultState.SHOPbaseurl : defaultState.baseurl) + data.url,
            method: data.method,
            data: JSON.stringify(data.data),
            params: JSON.stringify(data.data), //data.method=='get'||data.method=='GET'?JSON.stringify(data.data):'',
            header,
            success: res => {

                if (defaultState.encryption) {
                    try {
                        res.data.data = res.data.data ? JSON.parse(decrypt(res.data.data)) : res.data.data
                    } catch (e) {
                        //TODO handle the exception
                    }
                }
                if (res.statusCode == 200) {
                    // console.log("接口放回的参数：",res.data)
                    // uni.removeStorageSync('str')
                    data.success(res.data);
                } else if (res.statusCode == 403) {
                    if(isHop){
                        uni.switchTab({
                            url: '/pages/personal/index'
                        });
                    }else{

                    const {fullPath} = getLoction()
                    uni.setStorageSync('str', fullPath)

                    uni.setStorageSync('userInfo', {});
                    // #ifdef MP-WEIXIN
                    uni.switchTab({
                        url: '/pages/personal/index'
                    });
                    // #endif
                    // #ifndef MP-WEIXIN
                    uni.reLaunch({
                        url: '/pages/login/login'
                    });
                    // #endif
                    }

                } else if (res.statusCode === 400) {
                    if(!isHop){
                        uni.reLaunch({
                            url: '/pages/stop/stop'
                        });
                    }

                } else if (res.statusCode === 429) {

                } else {

                }

            },
            fail(e) {
            }

        });
    }
}

export const request = requsetBaseFn()
export const requestHop = requsetBaseFn(true)
export const requestPromise = async (data) => {
    let token = '';
    let p = ''
    try {
        p = uni.getStorageSync('userInfo').p
    } catch (e) {
    }
    try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.token) {
            token = userInfo.token;
        }
    } catch (e) {
        //TODO handle the exception
        console.error('Error getting token from storage:', e);
    }
    console.error('token:', token);
    const response = await new Promise((resolve, reject) => {
        uni.request({
            url: defaultState.baseurl + data.url,
            method: data.method,
            data: data.method === 'GET' ? {} : JSON.stringify(data.data), // 注意：GET 请求通常不使用 data 字段发送数据
            params: data.method === 'GET' ? data.data : {}, // 注意：params 用于 GET 请求的查询参数
            header: {
                'p': p, 'token': token, 'encryption': defaultState.encryption
            },
            success: res => {
                if (defaultState.encryption) {
                    try {
                        res.data.data = JSON.parse(decrypt(res.data.data))
                    } catch (e) {
                        //TODO handle the exception
                    }
                }
                if (res.statusCode === 200) {
                    resolve(res.data);
                    reject(res);
                } else if (res.statusCode === 403) { // 处理错误情况，例如重新登录、显示错误信息等
                    uni.setStorageSync('userInfo', {});
                    // #ifdef MP-WEIXIN
                    uni.switchTab({
                        url: '/pages/personal/index'
                    });
                    // #endif
                    // #ifndef MP-WEIXIN
                    uni.reLaunch({
                        url: '/pages/login/login'
                    });
                    // #endif
                } else if (res.statusCode === 400) {
                    uni.reLaunch({
                        url: '/pages/stop/stop'
                    });
                } else {
                    // 处理其他错误情况
                    console.error('Request failed:', error);
                }

            },
            fail: e => {
                reject(e);
            }
        });
    });
    return response; // 返回响应数据，以便在 async 函数外部使用
};

// 仅在App端有效
let hasPermission = false;
export async function checkAndRequestStoragePermission(permission = 'android.permission.CAMERA') {

    // 主动申请权限
    return new Promise((resolve) => {
        //#ifdef H5
        resolve(true);
        //#endif
        if (hasPermission) {
            resolve(true);
        }
        // const permission = "android.permission.WRITE_EXTERNAL_STORAGE";
        if (plus.android.checkPermission(permission)) {
            // 已有权限
            resolve(true);
        }
        plus.android.requestPermissions([permission], (result) => {
            resolve(result.granted.length > 0);
            hasPermission = true;
            resolve(true)
        }, () => {
            resolve(false);
        });
    });
}

export const Uplode = async (uploadSuccess, i, count = 1) => { //全局上传图片(uploadSuccess回调函数)
    const hasPermission = await checkAndRequestStoragePermission();
    if (!hasPermission) {
        return;
    }
    let token = ''
    try {
        token = uni.getStorageSync('userInfo').token
    } catch (e) {

    }
    uni.request({
        url: defaultState.baseurl + 'api/token/', method: 'GET', header: {
            'token': token
        }, success: res => {
            if (defaultState.encryption) {
                try {
                    res.data.data = JSON.parse(decrypt(res.data.data))
                } catch (e) {
                    //TODO handle the exception
                }

            }
            let upload = res.data.data
            setTimeout(() => {
                // #ifndef MP-WEIXIN
                uni.chooseImage({
                    count: count, //默认9
                    sizeType: ['original', 'compressed'], sourceType: ['album', 'camera '], success: (ress) => {
                        let type
                        // #ifdef APP-PLUS
                        type = ress.tempFilePaths[0].split('.')
                        type = type[type.length - 1]
                        // #endif
                        // #ifndef APP-PLUS
                        type = ress.tempFiles[0].name.split('.')
                        type = type[type.length - 1]
                        // #endif
                        console.log(ress)
                        ress.tempFilePaths.forEach((item, index) => {
                            uni.uploadFile({
                                url: upload.upload, //仅为示例，非真实的接口地址
                                filePath: item, name: 'file', header: {
                                    token: upload.token
                                }, formData: {
                                    key: defaultState.template + '/' + String(Math.round(new Date() / 1000)) + String(parseInt(Math
                                        .random() * 10000)) + '.' + type, token: upload.token
                                }, header: {
                                    token: upload.token
                                }, success: (uploadFileRes) => {
                                    let obj = {
                                        data: ress
                                    }
                                    uploadSuccess(upload.url + JSON
                                        .parse(uploadFileRes.data).key, obj, i)


                                }
                            });

                        })
                    }, fail() {
                        // uni.showToast({
                        //     icon: 'none',
                        //     title: '123'
                        // })
                    }
                });
                // #endif
                // #ifdef MP-WEIXIN
                uni.chooseMedia({
                    mediaType: ['image'],
                    count: 9, //默认9
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album', 'camera'],
                    camera: 'back',
                    success: (ress) => {
                        let type = ress.tempFiles[0].tempFilePath
                        type = type[type.length - 1]
                        uni.uploadFile({
                            url: upload.upload, //仅为示例，非真实的接口地址
                            filePath: ress.tempFiles[0].tempFilePath, name: 'file', header: {
                                token: upload.token
                            }, formData: {
                                key: defaultState.template + '/' + String(Math.round(new Date() / 1000)) + String(parseInt(Math
                                    .random() * 10000)) + '.' + type, token: upload.token
                            }, header: {
                                token: upload.token
                            }, success: (uploadFileRes) => {
                                let obj = {
                                    data: ress
                                }
                                uni.hideLoading();
                                uploadSuccess(upload.url + JSON
                                    .parse(uploadFileRes.data).key, obj, i)
                            }
                        });
                    },
                    fail() {
                        console.log(fail)
                    }
                });
                // #endif
            }, 100)

        }, fail(e) {
        }

    });
}
export const UplodeVideo = (uploadSuccess,) => { //全局上传图片(uploadSuccess回调函数)
    let token = ''
    try {
        token = uni.getStorageSync('userInfo').token
    } catch (e) {
    }
    uni.request({
        url: defaultState.baseurl + 'api/token/', method: 'GET', header: {
            'token': token
        }, success: res => {
            if (defaultState.encryption) {
                try {
                    res.data.data = JSON.parse(decrypt(res.data.data))
                } catch (e) {
                    //TODO handle the exception
                }

            }
            console.log(res)
            let upload = res.data.data
            setTimeout(() => {
                uni.chooseVideo({
                    sizeType: ['original', 'compressed'], sourceType: ['album', 'camera '], success: (ress) => {

                        console.log(ress.tempFilePath)
                        let type
                        if (ress.tempFile) {
                            type = ress.tempFile.name.split('.')
                            type = type[type.length - 1]
                        } else {
                            type = ress.tempFilePath.split('.')
                            type = type[type.length - 1]
                        }

                        // let type
                        // // #ifdef APP-PLUS
                        // type = ress.tempFilePaths.split('.')
                        // // type = type[type.length - 1]
                        // // #endif
                        // // #ifndef APP-PLUS
                        // type = ress.tempFilePaths.name.split('.')
                        // // type = type[type.length - 1]
                        // // #endif
                        uni.uploadFile({
                            url: upload.upload, //仅为示例，非真实的接口地址
                            filePath: ress.tempFilePath, name: 'file', header: {
                                token: upload.token
                            }, formData: {
                                key: defaultState.template + '/' + String(Math.round(new Date() / 1000)) + String(parseInt(Math
                                    .random() * 10000)) + '.' + type, token: upload.token
                            }, header: {
                                token: upload.token
                            }, success: (uploadFileRes) => {
                                uploadSuccess(upload.url + JSON
                                    .parse(uploadFileRes.data).key)

                                console.log(JSON.parse(uploadFileRes.data), '12321')
                            }
                        });
                    }, fail(fail) {
                        console.log(fail)
                    }
                });

            }, 100)
        }, fail(e) {
        }

    });
}
